package com.cby.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/uploadPage")
    public ModelAndView uploadPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("111111111111111");
        ModelAndView mv = new ModelAndView("/fileUpload");
        return mv;
    }

    @RequestMapping(value = "/upload",headers = "content-type=multipart/*", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        //存在问题：无法识别@RequestParam这个注解在jsp对应的属性
        System.out.println(file);
        if (file != null && !file.isEmpty()) {
            //上传文件路径
            String path = "/Users/chenbaoyang/";

            System.out.println(path);

            //上传的文件名
            String fileName = file.getOriginalFilename();
            File fileDest = new File(path, fileName);

            //判断文件要存储的目录是否存在
            if (!fileDest.getParentFile().exists()) {
                fileDest.getParentFile().mkdirs();
            }

            //将上传的文件保存到目标目录中
            String destPath = path + File.separator + fileName;
            try {
                file.transferTo(new File(destPath));
            } catch (IOException e) {
                e.printStackTrace();
            }

            System.out.println(destPath);
            return "1";
        }
        return "0";
    }
}
